# -*- coding: utf-8 -*-
"""
 ----------------------------------------
|File Name:     login_test
|Author:        WYT
|date:          2020/11/18
 ----------------------------------------
|  Change Activity:
|                   2020/11/18:
-----------------------------------------
"""
import html
import json
import time
import urllib
from base64 import b64encode

import requests
# from gmssl import sm2
from gmssl import sm2, func, sm3
from gmssl.sm2 import CryptSM2

from base.BaseMethod import BM
from util.GetValidateCodeImg import GetImg
from util.Logger import Logger
from util.encryption_password.core import CryptoJS
from util.selenium import webdriver
from util.selenium.webdriver import ChromeOptions, DesiredCapabilities

from settings import validate_code_path, username, password, soft_id, chrome_driver_path, start_url, log_path
from util.chaojiying import Chaojiying_Client
from util.g import g
from util.selenium.webdriver.common.by import By


class LoginPage():
    login_iframe_loc = (By.XPATH, "//iframe[contains(@src, 'https://fuwu.most.gov.cn/authentication/sso/gjzwfw3/login')]")
    cjy = Chaojiying_Client(username=username, password=password, soft_id=soft_id)
    cookie = None

    def __init__(self, driver):
        self.driver = driver

    def login(self, c_username='91110108MA01EMR49Y', c_userpwd='Hz123456'):
        # 传入 driver 用于获取 加密后的密码
        url = "https://fuwu.most.gov.cn/authentication/sso/login"
        headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) '
                          'Chrome/71.0.3554.0 Safari/537.36'
        }
        log_res = requests.get(url=url, headers=headers)
        cookie_jar = log_res.cookies
        cookie_dict = cookie_jar.get_dict()
        headers["Cookie"] = "; ".join([k + "=" + v for k, v in cookie_dict.items()])
        validatecode_url = "https://fuwu.most.gov.cn/authentication/servlet/validateCodeServlet?width=88&height=38&v="
        res = requests.get(url=validatecode_url, headers=headers)
        img_path = '{}{}_validate_code_img.jpg'.format(validate_code_path, time.strftime('%Y-%m-%d %H-%M-%S')).replace(
            '\\', '/')
        with open(img_path, 'wb') as f:
            f.write(res.content)

        login_url = "https://fuwu.most.gov.cn/authentication/sso/login"
        data = {
            "key": "",
            "response_type": "",
            "state": "",
            "userType": "legal",
            "loginName": c_username,
            "password": "",
            "password_pbe": "",
            "validateCode": "",
        }
        if g.is_test:
            data["validateCode"] = input("请输入验证码:")
        else:
            result_dict = self.cjy.PostPicPath(img_path=img_path)
            self.result_dict = result_dict
            data["validateCode"] = result_dict.get("pic_str")
        BM.switch_to_frame(driver=self.driver, ele_loc=self.login_iframe_loc)
        data["password"] = self.driver.execute_script("return sm_password('{}')".format(c_userpwd))
        data["password_pbe"] = self.driver.execute_script("return encode.encode64('{}')".format(c_userpwd))

        response = requests.post(url=login_url, json=data, headers=headers)
        print(response.status_code)
        print(response.cookies.get_dict())
        self.cookie = response.cookies.get_dict()

# 加密密码方法
def encode(b):
    key_str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\x3d"
    a = ""
    global h
    c, d, e, k, h, f, h = (0, 0, 0, 0, 0, 0, 0)
    # 实现 g++ 的功能

    def g_plus():
        global h
        a = h
        h += 1
        return a

    # 实现 js 中 isNan 方法
    def is_nan(num):
        flag = True
        try:
            int(num)
            flag = False
        except ValueError:
            pass

    # 实现 js 中 charAt 方法
    def char_code_at(b, index):
        num = len(b)
        if num - 1 < index:
            # return float("nan")
            return 0
        else:
            return ord(b[index])

    while True:
        # c = ord(b[g_plus()])
        # d = ord(b[g_plus()])
        # e = ord(b[g_plus()])
        c = char_code_at(b, g_plus())
        d = char_code_at(b, g_plus())
        e = char_code_at(b, g_plus())
        k = c >> 2
        c = (c & 3) << 4 | d >> 4
        h = (d & 15) << 2 | e >> 6
        f = e & 63
        if d == 0:
            h, f = 64, 64
        else:
            if e == 0:
                f = 64

        a = a + key_str[k] + key_str[c] + key_str[h] + key_str[f]
        if h >= len(b):
            return a


class CryptSM2(sm2.CryptSM2):

    def encrypt(self, data, is_to_bytes=False):
        # 加密函数，data消息(bytes)
        msg = data.hex() # 消息转化为16进制字符串
        k = func.random_hex(self.para_len)
        C1 = self._kg(int(k,16),self.ecc_table['g'])
        xy = self._kg(int(k,16),self.public_key)
        x2 = xy[0:self.para_len]
        y2 = xy[self.para_len:2*self.para_len]
        ml = len(msg)
        t = sm3.sm3_kdf(xy.encode('utf8'), ml/2)
        if int(t,16)==0:
            return None
        else:
            form = '%%0%dx' % ml
            C2 = form % (int(msg, 16) ^ int(t, 16))
            C3 = sm3.sm3_hash([
                i for i in bytes.fromhex('%s%s%s'% (x2,msg,y2))
            ])
            res_str = "{}{}{}".format(C1, C2, C3)
            if is_to_bytes:
                return bytes.fromhex(res_str)
            return res_str



# sm2 加密密码方法
def sm_password(b):
    sm2_public_key = "049c3e914350086279c0a09ae2e6056d87734bf6d03d33a5d70aad9cb0412abed463e" \
                      "bc5e8510318b5e8cc0a70f14f079e7aa8fb36d561425fe85ed2970168c9ae"
    sm2_crypt = CryptSM2(public_key=sm2_public_key, private_key="")
    b = urllib.parse.unquote(b)
    b = html.unescape(b)
    encode_info = sm2_crypt.encrypt(b.encode(encoding="utf-8"))
    # encode_info = b64encode(encode_info).decode(encoding="utf-8")
    return encode_info




if __name__ == '__main__':
    """
    04c587215535f71c9d36e4ae977bc6d90660e2f4d0c544c7f17751e744c7d935062359e0f4c7676e47672eb77bc0819ee892a198f79f64d42562824ae3a280f415fa384cd0a75c5938ac655c428c51dc786f1734df5eba6d780d7d8cdfb50d8273076968940383b740
    """
    a = CryptoJS()
    res = a.enc_Utf8_parse("Hz123456")
    print(sm_password(res))
    # print(encode("Hz123456"))


    pass
    # g.logger = Logger(log_file_name=log_path.replace("log.txt", "test_request.log"), log_level=Logger.DEBUG,
    #                   logger_name="test_request").get_log()
    # s = "SHoxMjM0NTY="
    # headers = {
    #     "User-Agent": "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.77 Safari/537.36",
    #     "Connection": "Close"
    # }
    # login_url = "https://fuwu.most.gov.cn/authentication/sso/login"
    # login_page_res = requests.get(login_url, headers=headers, allow_redirects=False)
    # # print(dict(login_page_res.cookies))
    # # g.logger.info(login_page_res.content.decode("utf-8"))
    #
    # cookies_dict = login_page_res.cookies
    #
    # c_username = "91320411MA20201Y6Q"
    # c_password = "Hz123456"
    #
    # login_data = {
    #     "key": "",
    #     "response_type": "",
    #     "state": "",
    #     "userType": "legal",
    #     "loginType": "",
    #     "loginName": c_username,
    #     "password": sm_password(c_password),
    #     "password_pbe": encode(c_password),
    #     "validateCode": "",
    # }
    #
    # image_path = GetImg(cookies_dict=cookies_dict).get_img()
    # cjy = Chaojiying_Client(username=username, password=password, soft_id=soft_id)
    #
    # result_dict = cjy.PostPicPath(img_path=image_path)
    # g.logger.info("验证码识别：{}".format(json.dumps(result_dict)))
    # validate_code_value = result_dict.get("pic_str")
    # login_data["validateCode"] = validate_code_value
    #
    # headers["Cookie"] = "; ".join("{}={}".format(k, v) for k, v in cookies_dict.items())
    #
    # logint_res = requests.post(login_url, data=login_data, headers=headers, allow_redirects=False)
    # print(dict(logint_res.cookies))
    # g.logger.info(logint_res.content.decode("utf-8"))

